<template>
	<view class="merchantInto">
        <SRV-topbar title="修改资料" :isLeft="true"></SRV-topbar>
	    <view class="line">
			<view class="left"><span>*</span>店铺名称：</view>
			<view class="right">
				<input type="text" v-model="formData.title" disabled style="background-color: #ccc;"/>
			</view>
		</view>
		<view class="line">
			<view class="left"><span>*</span>联系人：</view>
			<view class="right">
				<input type="text" v-model="formData.name" placeholder="请输入联系人姓名" />
			</view>
		</view>
		<view class="line">
			<view class="left"><span>*</span>手机号：</view>
			<view class="right">
				<input type="number" v-model="formData.mobile" placeholder="请输入手机号码" />
			</view>
		</view>
		<view class="line" style="border-bottom: none;padding-bottom: 0;">
			<view class="left"><span>*</span>店铺位置：</view>
			<view class="right">
                <input type="text" disabled v-model="formData.address_name"  @click="getMapLocation()"/>
			</view>
		</view>
		<view class="line">
            <textarea  v-model="formData.address_details" placeholder="请填写详细地址，不少于5个字" />
		</view>
        <view class="line" style="border-bottom: none;padding-bottom: 0;">
        	<view class="left">店铺公告：</view>
        </view>
        <view class="line">
            <textarea  v-model="formData.description" value="" placeholder="请填写店铺公告" />
        </view>
		<view class="line">
			<view class="imgTd">
				<view><span>*</span>营业执照</view>
                <image :src="formData.logoUrl" mode="aspectFill" @click="chooseImage('logo', 1)"></image>
			</view>
            <view class="imgTd" style="border-right: none;">
            	<view><span>*</span>门店照</view>
                <image :src="formData.coverUrl" mode="aspectFill" @click="chooseImage('cover', 1)"></image>
            </view>
		</view>
        <view class="line" style="border-bottom: none;padding-bottom: 0;">
        	<view class="left" style="width: 30%;">店铺详情图：</view>
        </view>
		<view class="photos">
		    <view class="photo_list" v-for="(uploadItem,index) in formData.imgList" :key="index">
		        <image :src="uploadItem.thumb" mode="aspectFill" @tap="previewImage"
		            :data-src="uploadItem.imgUrl" :data-id="index"></image>
		        <image @click="delImg(index)" src="https://hdsq.aoorange.cn/attachment/xcx/icon/del-new.png" class="del" mode="aspectFill"></image>
		    </view>
		    <image src="https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png" mode="aspectFill"
		        @click="chooseImage('covers', 9)"></image>
		</view>
		<view class="bottom" @click="save">确定修改</view>
	</view>
</template>

<script>
	var _self;
	import pickRegions from '@/components/pick-regions/pick-regions.vue';
	import serve from '../static/request.js';
	import storage from '../static/appkey.js';
	import common from '../static/jump.js';
	import wechatPay from '../static/wechatPay.js';
	export default {
		components: {
			pickRegions
		},
		data() {
			return {
                id: 0,
				formData: {
					appkey: uni.getStorageSync('appkey'),
					'access-token': uni.getStorageSync('access-token'),
                    title : '',
                    name: '',
                    mobile: '',
                    address_name: '请点击选择地图',
                    address_details: '',
                    longitude: '',
                    latitude: '',
                    coverUrl: 'https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png',
                    cover: '',
                    logoUrl: 'https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png',
                    logo: '',
                    description: '',
                    imgList: [],
				},
                parentInfo: '',
				isSubmit: false,
				isclick: false,
				isLoad: false,
				logoUrl: '',
				coversList: [],
				imgList: [],
			}
		},
		methods: {
			getMapLocation(){
				_self.isLoad = true;
				wx.chooseLocation({
					'longitude': _self.formData.longitude,
					'latitude': _self.formData.latitude,
					success:(res)=> {
                        const locationObj = res.address;
                        const provinceRegex = /^(.*?[省|自治区|特别行政区])/;
                        const provinceMatch = locationObj.match(provinceRegex);
                        const province = provinceMatch ? provinceMatch[1] : '';
                        const cityRegex = new RegExp(province+'(.*?市)');
                        const cityMatch = locationObj.match(cityRegex);
                        const city = cityMatch ? cityMatch[1] : '';
                        const districtRegex = new RegExp(city+'(.*?区)');
                        const districtMatch = locationObj.match(districtRegex);
                        const area = districtMatch ? districtMatch[1] : '';
                        _self.formData.address_name = province + " "+city+" "+area;
						_self.formData.address_details = res.name;
						_self.formData.longitude = res.longitude;
						_self.formData.latitude = res.latitude;
						_self.$forceUpdate();
						// this.getRegionFn(res);
					},
					fail:()=>{
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						uni.getSetting({
							success: (res) => {
								var status = res.authSetting;
								if(!status['scope.userLocation']){
								// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title:"是否授权当前位置",
										content:"需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success:(tip)=>{
											if(tip.confirm){
											// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success:(data)=>{
													// 如果用户授权了地理信息在，则提示授权成功
														if(data.authSetting['scope.userLocation']===true){
															uni.showToast({
																title:"授权成功",
																icon:"success",
																duration:1000
															})
															// 授权成功后，然后再次chooseLocation获取信息
															uni.chooseLocation({
																success: (res) => {
																	console.log("详细地址",res);
																	// this.getRegionFn(res);
																}
															})
														}else{
															uni.showToast({
																title:"授权失败",
																icon:"none",
																duration:1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title:"调用授权窗口失败",
									icon:"none",
									duration:1000
								})
							}
						})
					}
				});
			},
			getInfo() {
				serve.request({
					url: '/member/merchant/detail',
					data: {
						appkey: uni.getStorageSync('appkey'),
						'access-token': uni.getStorageSync('access-token'),
                        type: 'detail',
                        id: _self.id
					},
                    v: '/v3',
				}).then(res => {
					if (res.code == 200) {
                        _self.formData.id = res.data.id;
                        _self.formData.title = res.data.title;
                        _self.formData.name = res.data.name;
                        _self.formData.mobile = res.data.mobile;
                        _self.formData.description = res.data.description;
                        _self.formData.cover = res.data.cover;
                        _self.formData.coverUrl = res.data.coverUrl;
                        _self.formData.logo = res.data.logo;
                        _self.formData.logoUrl = res.data.logoUrl;
                        _self.formData.address_name = res.data.address_name;
                        _self.formData.address_details = res.data.address_details;
                        _self.formData.longitude = res.data.longitude;
                        _self.formData.latitude = res.data.latitude;
                        _self.formData.imgList = res.data.imgList;
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							success() {
								setTimeout(function() {
									uni.redirectTo({
										url: '/pages/index/index'
									});
								}, 2000)
							}
						});
					}
				});
			},
			async save() {
				if (_self.isSubmit) {//防止重复提交
					return;
				}
				if (_self.formData.title == "") {
					uni.showToast({
						title: "请填写商铺名称",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.name == "") {
					uni.showToast({
						title: "请填写联系人",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.mobile == "") {
					uni.showToast({
						title: "请填写联系电话",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.longitude == "" || _self.formData.latitude == "") {
					uni.showToast({
						title: "请点击地图获取经纬度",
						icon: 'none'
					})
					return;
				}
				if (_self.formData.address == "") {
					uni.showToast({
						title: "请填写详细地址",
						icon: 'none'
					})
					return;
				}
                if (_self.formData.logoUrl == "https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png") {
                	uni.showToast({
                		title: "请上传营业执照",
                		icon: 'none'
                	})
                	return;
                }
				if (_self.formData.coverUrl == "https://hdsq.aoorange.cn/attachment/xcx/icon/addphoto.png") {
					uni.showToast({
						title: "请上传门头照",
						icon: 'none'
					})
					return;
				}
				if(_self.formData.logo == '') {
					let uresult = await _self.uploadFileFun(_self.formData.logoUrl);
					if (!uresult) {
					    uni.showToast({
					        title: "营业执照上传失败",
					        icon: 'none'
					    });
					    return;
					}
					_self.formData.logo = uresult;
				}
                if(_self.formData.cover == '') {
                	let uresult = await _self.uploadFileFun(_self.formData.coverUrl);
                	if (!uresult) {
                	    uni.showToast({
                	        title: "门头照上传失败",
                	        icon: 'none'
                	    });
                	    return;
                	}
                	_self.formData.cover = uresult;
                }
				for(let kk = 0; kk < _self.formData.imgList.length; kk ++) {
					let it = _self.formData.imgList[kk];
					if(it.isUpload == 0) {
						let uresult = await _self.uploadFileFun(it.imgUrl);
						if (!uresult) {
						    uni.showToast({
						        title: "店铺详情第" + (Number(kt) + Number(1)) +"张图片上传失败",
						        icon: 'none'
						    });
						    return;
						}
						it.imgPath = uresult;
						it.isUpload = 1;
					}
				}
                uni.showLoading({
                	title: '提交中···',
                	mask: true
                });
				serve.request({
					url: '/member/merchant/edit',
					data: _self.formData,
                    v: '/v3',
				}, 'POST').then(res => {
                    uni.hideLoading();
					uni.showToast({
						title: res.message,
						icon: 'none',
					});
					if (res.code == 200) {
						uni.redirectTo({
						    url: '/merchant/detail?id='+_self.id
						});
						return ;
					}
					_self.isSubmit = false;
					
				});
				_self.isSubmit = true;
			},
			
			chooseImage(type, surplusNum = 1) {
				_self.isLoad = true;
                if(surplusNum * 1 > 1 * 1) {
                    if(type == 'covers' && _self.formData.imgList.length >= Number(surplusNum)) {
                        uni.showToast({
                            title: "店铺详情图只能上传"+surplusNum+"张",
                            icon: 'none'
                        });
                        return;
                    }
                }
			    uni.chooseImage({
			        count: surplusNum,
			        sizeType: ['original'],
			        sourceType: ['album'],
			        success: (chooseImageRes) => {
			            const tempFilePaths = chooseImageRes.tempFiles;
			            tempFilePaths.forEach((file, key) => {
			                const maxSize = 10 * 1024 * 1024;
			                // console.info("file.size = " + file.size);
			                if (file.size > maxSize) {
			                    uni.showToast({
			                        icon: "none",
			                        title: "文件不能大于10兆",
			                        mask: true,
			                        duration: 1.5e3
			                    });
			                    return;
			                } else {
								if(type == 'logo') {
									_self.formData.logo = '';
									_self.formData.logoUrl = file.path;
									return ;
								}
                                if(type == 'cover') {
                                	_self.formData.cover = '';
                                	_self.formData.coverUrl = file.path;
                                	return ;
                                }
                                if(type == 'covers') {
                                	let temp = {
                                		thumb: file.path,
                                	    imgUrl: file.path,
                                	    isUpload: 0,
                                	    imgPath: ''
                                	};
                                	_self.formData.imgList.push(temp);
                                	return ;
                                }
			                }
			            });
			            _self.$forceUpdate();
			        }
			    });
			},
			previewImage: function(e) {
			    var current = e.target.dataset.src;
			    uni.previewImage({
			        current: current,
			        urls: _self.imgList
			    });
			    return;
			},
			delImg(key) {
			    _self.formData.imgList.splice(key, 1);
			    _self.$forceUpdate();
			},
			async uploadFileFun(file) {
			    let accessToken = uni.getStorageSync('access-token');
			    let appkey = uni.getStorageSync('appkey');
			    return new Promise((resolve, reject) => {
			        uni.uploadFile({
			            url: serve.apiUrl() + '/v1/file/images?appkey=' + appkey +
			                '&access-token=' + accessToken,
			            filePath: file,
			            name: 'file',
			            formData: {},
			            success: (uploadFileRes) => {
			                let result = JSON.parse(uploadFileRes.data);
			                console.info(result);
			                if (result.code == 200) {
			                    resolve(result.data.imgPath);
			                } else {
			                    resolve(false);
			                }
			            }
			        });
			    });
			},
			jump(jump_type, jump_link) {
				common.jump(jump_type, jump_link);
			}
		},
		onLoad(option) {
            _self = this;
            _self.id = option.id || 0;
			_self.getInfo();
		},
		onPullDownRefresh() {
            _self.getInfo();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		}
	}
</script>

<style scoped lang="scss">
	.merchantInto{
		padding-bottom: 100upx;
		.main{
			width:100%;
			height:360upx;
		}
		.heng{
			width: 100%;
			height: 12upx;
			background: #F8F8FA;
		}
		.nobottom{
			border: none !important;
		}
		.deal{
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24upx;
			padding: 20upx 0upx;
			text:nth-child(2){
				color: #999999;
				margin-left: 11upx;
			}
			text:nth-child(3){
				color: #EB5938;
				margin-left: 11upx;
			}
			.sel {
				background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/icon37.png);
				background-repeat: no-repeat;
				width:30upx;
				height:30upx;
				background-size: 100%;
				margin-right: 20upx;
			}
			
			.nosel {
				width: 30upx;
				height: 30upx;
				border: 1upx solid #999999;
				border-radius: 50%;
				margin-right: 20upx;
			}
		}
		.bottom{
			position: fixed;
			bottom: 0;
			width:100%;
			height:100upx;
			line-height: 100upx;
			text-align: center;
			color: #FFFFFF;
			font-size: 28upx;
			background:rgba(255,188,0,1);
			z-index: 9;
		}
		.title{
			color: #666666;
			font-size: 32upx;
			font-weight: bold;
			padding-top: 52upx;
			padding-left: 30upx;
		}
		.line{
			position: relative;
            width: 100%;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            padding: 20rpx 30rpx;
            border-bottom: 1rpx #EBEBEB solid;
            .left {
                font-size: 32rpx;
                width: 27%;
                text-align: right;
            }
            .right{
                width: 70%;
                input {
                    font-size: 32rpx;
                    border: 1rpx solid #ccc;
                    height: 60rpx;
                    padding-right: 10rpx;
                    padding: 5rpx 20rpx;
                    border-radius: 20rpx;
                    width: 100%;
                }
            }
            
            textarea {
                font-size: 32rpx;
                border: 1rpx solid #ccc;
                height: 80rpx;
                padding-right: 10rpx;
                padding: 20rpx;
                border-radius: 20rpx;
                width: 100%;
            }
        }
		.imgTd {
            width: 50%;
            text-align:center;
            border-right: 1rpx #ebebeb solid;
            image {
                width: 200rpx;
                height: 200rpx;
            }
        }
	}
    
    span {
        color: red;
    }
		.photos {
		    box-sizing: border-box;
		    padding: 30upx 30upx;
		    display: flex;
		    flex-wrap: wrap;
		
		    image {
		        width: 150upx;
		        height: 150upx;
		        border-radius: 10upx;
		        margin-bottom: 20upx;
		    }
		
		    .photo_list {
		        margin-right: 30upx;
		        padding-bottom: 20upx;
		        display: flex;
		        flex-direction: column;
		        align-items: flex-end;
		        position: relative;
		
		        view {
		            color: red;
		            font-size: 30upx;
		        }
		
		        .del {
		            width: 48upx !important;
		            position: absolute;
		            height: 48upx !important;
		            top: -24upx;
		            right: -24upx;
		        }
		    }
		}
</style>